<template>
  <div class="posts-management">
    <!-- 页面标题和操作栏 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
      <div>
        <h2 class="page-title mb-1">帖子管理</h2>
        <p class="text-muted mb-0">管理系统所有帖子，支持查看、编辑、删除等操作</p>
      </div>
      <div class="d-flex gap-2">
        <button class="btn btn-outline-secondary">
          <i class="bi bi-download me-2"></i>导出数据
        </button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="row mb-4">
      <div class="col-xl-3 col-md-6 mb-3">
        <div class="card stat-card bg-primary text-white">
          <div class="card-body">
            <div class="d-flex align-items-center">
              <div class="flex-grow-1">
                <h4 class="card-title">{{ stats.totalPosts }}</h4>
                <p class="card-text mb-0">总帖子数</p>
              </div>
              <div class="stat-icon">
                <i class="bi bi-file-earmark-text"></i>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-xl-3 col-md-6 mb-3">
        <div class="card stat-card bg-warning text-white">
          <div class="card-body">
            <div class="d-flex align-items-center">
              <div class="flex-grow-1">
                <h4 class="card-title">{{ stats.topPosts }}</h4>
                <p class="card-text mb-0">热门帖子</p>
              </div>
              <div class="stat-icon">
                <i class="bi bi-fire"></i>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-xl-3 col-md-6 mb-3">
        <div class="card stat-card bg-info text-white">
          <div class="card-body">
            <div class="d-flex align-items-center">
              <div class="flex-grow-1">
                <h4 class="card-title">{{ stats.categories }}</h4>
                <p class="card-text mb-0">帖子分类</p>
              </div>
              <div class="stat-icon">
                <i class="bi bi-tags"></i>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选栏 -->
    <div class="card mb-4">
      <div class="card-body">
        <div class="row g-3 align-items-end">
          <div class="col-md-3">
            <label class="form-label">关键词搜索</label>
            <div class="input-group">
              <span class="input-group-text">
                <i class="bi bi-search"></i>
              </span>
              <input type="text" class="form-control" placeholder="搜索帖子标题、内容..." v-model="searchQuery"
                @input="handleSearch">
            </div>
          </div>
          <div class="col-md-2">
            <label class="form-label">帖子分类</label>
            <select class="form-select" v-model="filters.category" @change="handleFilterChange">
              <option value="">全部分类</option>
              <option v-for="category in categories" :key="category.id" :value="category.id">
                {{ category.name }}
              </option>
            </select>
          </div>
          <div class="col-md-2">
            <label class="form-label">是否紧急</label>
            <select class="form-select" v-model="filters.isUrgent" @change="handleFilterChange">
              <option value="">全部</option>
              <option value="true">紧急</option>
              <option value="false">普通</option>
            </select>
          </div>
          <div class="col-md-2">
            <label class="form-label">帖子状态</label>
            <select class="form-select" v-model="filters.status" @change="handleFilterChange">
              <option value="">全部状态</option>
              <option value="pending">待审核</option>
              <option value="approved">已通过</option>
              <option value="rejected">已拒绝</option>
              <option value="sold">已售出</option>
            </select>
          </div>
          <div class="col-md-2">
            <label class="form-label">排序方式</label>
            <select class="form-select" v-model="filters.sortBy" @change="handleFilterChange">
              <option value="createdAt">创建时间</option>
              <option value="viewCount">浏览量</option>
              <option value="likeCount">点赞数</option>
            </select>
          </div>
          <div class="col-md-1">
            <label class="form-label">排序</label>
            <select class="form-select" v-model="filters.sortOrder" @change="handleFilterChange">
              <option value="desc">降序</option>
              <option value="asc">升序</option>
            </select>
          </div>
          <div class="col-md-12 mt-2">
            <button class="btn btn-outline-secondary" @click="resetFilters">
              <i class="bi bi-arrow-clockwise me-2"></i>重置筛选
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 帖子列表 -->
    <div class="card">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="card-title mb-0">帖子列表</h5>
        <div class="d-flex align-items-center gap-2">
          <span class="text-muted small">共 {{ pagination.total }} 个帖子</span>
        </div>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-hover align-middle mb-0">
            <thead class="table-light">
              <tr>
                <th width="100">
                  <div class="d-flex justify-content-center align-items-center">
                    <span 
                      class="fw-bold text-primary" 
                      style="cursor: pointer; font-size: 1rem;" 
                      @click="toggleSelectAll"
                    >
                      {{ selectAll ? '取消全选' : '全选' }}
                    </span>
                  </div>
                </th>
                <th width="80">封面</th>
                <th>帖子信息</th>
                <th>紧急</th>
                <th>作者</th>
                <th>分类</th>
                <th>统计数据</th>
                <th>状态</th>
                <th>创建时间</th>
                <th width="120">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="post in posts" :key="post.id" :class="{ 'table-active': selectedPosts.includes(post.id) }">
                <td>
                  <div class="form-check">
                    <input 
                      type="checkbox" 
                      class="form-check-input form-check-input-lg" 
                      :value="post.id"
                      v-model="selectedPosts"
                      :id="'post-check-' + post.id"
                    >
                    <label class="form-check-label" :for="'post-check-' + post.id"></label>
                  </div>
                </td>
                <td>
                  <img 
                    v-if="post.coverImageUrl" 
                    :src="post.coverImageUrl" 
                    alt="封面" 
                    class="rounded"
                    width="60" 
                    height="60"
                    @error="handleImageError"
                    @load="handleImageLoad(post.coverImageUrl)"
                  >
                  <img 
                    v-else 
                    :src="defaultPostCover" 
                    alt="默认封面" 
                    class="rounded" 
                    width="60" 
                    height="60"
                  >
                </td>
                <td>
                  <div class="d-flex flex-column">
                    <strong class="text-primary text-truncate" style="max-width: 200px;">{{ post.title }}</strong>
                    <small class="text-muted">{{ post.content.substring(0, 10) }}{{ post.content.length > 10 ? '...' :
                      '' }}</small>
                  </div>
                </td>
                <td>
                  <button 
                    v-if="post.isUrgent" 
                    class="btn btn-sm btn-danger px-2 py-1"
                    @click="toggleUrgentStatus(post)"
                  >
                    紧急
                  </button>
                  <button 
                    v-else
                    class="btn btn-sm btn-outline-secondary px-2 py-1"
                    @click="toggleUrgentStatus(post)"
                  >
                    普通
                  </button>
                </td>
                <td>
                  <div class="d-flex flex-column">
                    <strong>{{ post.author?.nickname || post.author?.username }}</strong>
                    <small class="text-muted">ID: {{ post.userId }}</small>
                  </div>
                </td>
                <td>
                  <span class="badge bg-primary">{{ getCategoryName(post.categoryId) }}</span>
                </td>
                <td>
                  <div class="d-flex flex-column">
                    <small><i class="bi bi-eye me-1"></i> {{ post.viewCount || 0 }}</small>
                    <small><i class="bi bi-hand-thumbs-up me-1"></i> {{ post.likeCount || 0 }}</small>
                    <small><i class="bi bi-bookmark me-1"></i> {{ post.favoriteCount || 0 }}</small>
                  </div>
                </td>
                <td>
                  <div class="d-flex flex-column">
                    <span class="status-badge" :class="'status-' + post.status">
                      {{ getStatusText(post.status) }}
                    </span>
                  </div>
                </td>
                <td>
                  <div class="d-flex flex-column">
                    <small class="text-muted">{{ formatDate(post.createdAt) }}</small>
                  </div>
                </td>
                <td>
                  <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-primary" @click="viewPost(post)" title="查看">
                      <i class="bi bi-eye"></i>
                    </button>
                    <button class="btn btn-outline-danger" @click="deletePost(post)" title="删除">
                      <i class="bi bi-trash"></i>
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 空状态 -->
        <div v-if="posts.length === 0" class="text-center py-5">
          <i class="bi bi-file-earmark-text display-1 text-muted"></i>
          <p class="text-muted mt-3">暂无帖子数据</p>
        </div>
      </div>

      <!-- 分页 -->
      <div class="card-footer d-flex justify-content-between align-items-center">
        <div class="text-muted small">
          显示第 {{ (pagination.currentPage - 1) * pagination.pageSize + 1 }} 到
          {{ Math.min(pagination.currentPage * pagination.pageSize, pagination.total) }} 条，共 {{ pagination.total }} 条
        </div>
        <nav>
          <ul class="pagination pagination-sm mb-0">
            <li class="page-item" :class="{ disabled: pagination.currentPage === 1 }">
              <button class="page-link" @click="changePage(pagination.currentPage - 1)">
                <i class="bi bi-chevron-left"></i>
              </button>
            </li>
            <li v-for="page in pagination.pages" :key="page" class="page-item"
              :class="{ active: page === pagination.currentPage }">
              <button class="page-link" @click="changePage(page)">{{ page }}</button>
            </li>
            <li class="page-item" :class="{ disabled: pagination.currentPage === pagination.totalPages }">
              <button class="page-link" @click="changePage(pagination.currentPage + 1)">
                <i class="bi bi-chevron-right"></i>
              </button>
            </li>
          </ul>
        </nav>
      </div>
    </div>

    <!-- 批量操作栏 -->
    <div v-if="selectedPosts.length > 0" class="batch-actions fixed-bottom bg-primary text-white p-4 shadow-lg">
      <div class="container-fluid">
        <div class="row align-items-center">
          <div class="col">
            <span class="h5 mb-0 text-white">已选择 <strong>{{ selectedPosts.length }}</strong> 个帖子</span>
          </div>
          <div class="col-auto">
            <div class="btn-group">
              <!-- 批量修改紧急状态按钮 -->
              <div class="btn-group me-2" role="group">
                <button type="button" 
                        class="btn btn-warning btn-lg text-white" 
                        @click="batchToggleUrgent">
                  <i class="bi bi-exclamation-triangle me-2"></i>批量切换紧急状态
                </button>
              </div>
              
              <!-- 批量修改状态按钮 -->
              <div class="btn-group me-2" role="group">
                <button type="button" 
                        class="btn btn-success btn-lg" 
                        @click="showBatchStatusModal">
                  <i class="bi bi-check-circle me-2"></i>批量修改状态
                </button>
              </div>
              
              <button class="btn btn-danger btn-lg" @click="batchDeletePosts">
                <i class="bi bi-trash me-2"></i>批量删除
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 批量修改状态模态框 -->
    <div class="modal fade" id="batchStatusModal" tabindex="-1" aria-labelledby="batchStatusModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg">
          <div class="modal-header bg-primary text-white">
            <h5 class="modal-title" id="batchStatusModalLabel">
              <i class="bi bi-check-circle me-2"></i>批量修改帖子状态
            </h5>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="text-center mb-4">
              <i class="bi bi-check-circle-fill text-primary" style="font-size: 3rem;"></i>
              <p class="mt-2 text-muted">请选择要更新的状态</p>
            </div>
            <form>
              <div class="mb-3">
                <label for="batchStatus" class="form-label fw-bold">帖子状态</label>
                <select class="form-select form-select-lg" id="batchStatus" v-model="batchStatus.newStatus">
                  <option value="pending">
                    <i class="bi bi-clock me-2"></i>待审核
                  </option>
                  <option value="approved">
                    <i class="bi bi-check-circle me-2"></i>已通过
                  </option>
                  <option value="rejected">
                    <i class="bi bi-x-circle me-2"></i>已拒绝
                  </option>
                  <option value="sold">
                    <i class="bi bi-currency-dollar me-2"></i>已售出
                  </option>
                </select>
                <div class="form-text">将为选中的 {{ selectedPosts.length }} 个帖子应用此状态</div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
              <i class="bi bi-x-circle me-2"></i>取消
            </button>
            <button type="button" class="btn btn-primary" @click="batchUpdateStatus">
              <i class="bi bi-check-circle me-2"></i>确认修改
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getPostAllService,
  getCategoriesListService,
  deletePostService,
  getPostCoverByIdService,
  updatePostService,
  batchUpdatePostStatusService // 引入新的批量更新状态服务
} from '@/api/post.js'
import { 
  getPostLikeCountService, 
  getPostFavoriteCountService 
} from '@/api/LikesFavorites.js'
import { getInternshipJobByPostId } from '@/api/Internship.js'
import defaultPostCover from '@/assets/images/封面加载失败.webp'

// 引入Bootstrap的Modal组件
import { Modal } from 'bootstrap'

// 响应式数据
const router = useRouter()
const posts = ref([])// 帖子列表
const categories = ref([])// 帖子类别
const searchQuery = ref('')
const allPosts = ref([]) // 存储所有帖子数据
const selectedPosts = ref([]) // 批量操作选中的帖子

// 图片加载状态
const imageLoadingStates = ref({})

// 批量状态修改
const batchStatus = reactive({
  newStatus: 'approved'
})

// 筛选条件
const filters = reactive({
  category: '',
  sortBy: 'createdAt',
  sortOrder: 'desc',
  isUrgent: '',
  status: '' // 添加状态筛选条件
})

// 统计数据
const stats = reactive({
  totalPosts: 0,
  topPosts: 0,
  categories: 0
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  totalPages: 0,
  pages: []
})

// 计算属性 - 全选状态
const selectAll = computed({
  get: () => posts.value.length > 0 && selectedPosts.value.length === posts.value.length,
  set: (value) => {
    if (value) {
      selectedPosts.value = posts.value.map(post => post.id)
    } else {
      selectedPosts.value = []
    }
  }
})

// 切换全选状态
const toggleSelectAll = () => {
  if (selectAll.value) {
    // 如果已经全选，则取消全选
    selectedPosts.value = []
  } else {
    // 如果没有全选，则全选所有帖子
    selectedPosts.value = posts.value.map(post => post.id)
  }
}

// 图片加载处理
const handleImageLoad = (imageUrl) => {
  if (imageUrl) {
    imageLoadingStates.value[imageUrl] = false
  }
}

// 图片加载错误处理
const handleImageError = (event) => {
  event.target.src = defaultPostCover
}

// 获取分类列表
const loadCategories = async () => {
  try {
    const response = await getCategoriesListService()

    if (response.code === 0) {
      categories.value = response.data
    } else {
      ElMessage.error('获取分类列表失败: ' + response.msg)
    }
  } catch (error) {
    ElMessage.error('获取分类列表失败: ' + error.message)
  }
}

// 根据分类ID获取分类名称
const getCategoryName = (categoryId) => {
  if (!categoryId) return '未分类'
  const category = categories.value.find(cat => cat.id === categoryId)
  return category ? category.name : '未分类'
}

// 方法
const loadPosts = async () => {
  try {
    // 获取所有帖子
    const response = await getPostAllService()
    console.log('获取所有帖子:', response)

    if (response.code === 0) {
      // 保存所有帖子数据
      allPosts.value = response.data
      
      // 在所有帖子数据上应用筛选条件
      let filteredPosts = [...response.data]

      // 关键字搜索
      if (searchQuery.value) {
        const keyword = searchQuery.value.toLowerCase()
        filteredPosts = filteredPosts.filter(post =>
          (post.title && post.title.toLowerCase().includes(keyword)) ||
          (post.content && post.content.toLowerCase().includes(keyword))
        )
      }

      // 分类筛选
      if (filters.category) {
        filteredPosts = filteredPosts.filter(post => post.categoryId === filters.category)
      }
      
      // 紧急状态筛选
      if (filters.isUrgent !== '') {
        const isUrgentValue = filters.isUrgent === 'true'
        filteredPosts = filteredPosts.filter(post => post.isUrgent === isUrgentValue)
      }
      
      // 状态筛选
      if (filters.status) {
        filteredPosts = filteredPosts.filter(post => post.status === filters.status)
      }

      // 排序
      filteredPosts.sort((a, b) => {
        let aValue, bValue
        switch (filters.sortBy) {
          case 'viewCount':
            aValue = a.viewCount || 0
            bValue = b.viewCount || 0
            break
          case 'likeCount':
            aValue = a.likeCount || 0
            bValue = b.likeCount || 0
            break
          default: // createdAt
            aValue = new Date(a.createdAt)
            bValue = new Date(b.createdAt)
        }

        if (filters.sortOrder === 'desc') {
          return bValue - aValue
        } else {
          return aValue - bValue
        }
      })

      // 更新统计数据（在筛选前）
      updateStatsWithFilteredData(filteredPosts)

      // 分页处理
      pagination.total = filteredPosts.length
      pagination.totalPages = Math.ceil(pagination.total / pagination.pageSize)
      updatePaginationPages()

      // 获取当前页数据
      const startIndex = (pagination.currentPage - 1) * pagination.pageSize
      const endIndex = startIndex + pagination.pageSize
      posts.value = filteredPosts.slice(startIndex, endIndex)

      // 为每个帖子获取封面图片并设置初始加载状态
      for (const post of posts.value) {
        try {
          // 获取帖子的点赞数和收藏数
          try {
            const likeCountResponse = await getPostLikeCountService(post.id)
            if (likeCountResponse.code === 0) {
              post.likeCount = likeCountResponse.data || 0
            }
          } catch (likeError) {
            console.error(`获取帖子 ${post.id} 点赞数失败:`, likeError)
            post.likeCount = 0
          }

          try {
            const favoriteCountResponse = await getPostFavoriteCountService(post.id)
            if (favoriteCountResponse.code === 0) {
              post.favoriteCount = favoriteCountResponse.data || 0
            }
          } catch (favoriteError) {
            console.error(`获取帖子 ${post.id} 收藏数失败:`, favoriteError)
            post.favoriteCount = 0
          }

          const coverResponse = await getPostCoverByIdService(post.id)
          if (coverResponse.code === 0 && coverResponse.data && coverResponse.data.length > 0) {
            const firstImage = coverResponse.data[0]
            post.coverImageUrl = firstImage.imageUrl.startsWith('http')
              ? firstImage.imageUrl
              : `http://localhost:8080${firstImage.imageUrl}`
            // 设置初始加载状态
            imageLoadingStates.value[post.coverImageUrl] = true
          } else {
            post.coverImageUrl = null
          }
        } catch (error) {
          console.error('获取帖子数据失败:', error)
          post.coverImageUrl = null
        }
      }
    } else {
      ElMessage.error('获取帖子列表失败: ' + response.msg)
    }
  } catch (error) {
    ElMessage.error('获取帖子列表失败: ' + error.message)
  }
}

// 统计数据（使用筛选后的数据）
const updateStatsWithFilteredData = (filteredPosts) => {
  stats.totalPosts = filteredPosts.length
  // 使用筛选后的帖子数据来统计热门帖子
  stats.topPosts = filteredPosts.filter(post => (post.viewCount || 0) > 50).length
  stats.categories = categories.value.length
}

// 分页
const updatePaginationPages = () => {
  const pages = []
  const startPage = Math.max(1, pagination.currentPage - 2)
  const endPage = Math.min(pagination.totalPages, startPage + 4)

  for (let i = startPage; i <= endPage; i++) {
    pages.push(i)
  }
  pagination.pages = pages
}

// 分页
const changePage = (page) => {
  if (page >= 1 && page <= pagination.totalPages && page !== pagination.currentPage) {
    pagination.currentPage = page
    // 重新加载帖子数据以应用当前筛选条件
    loadPosts()
  }
}

// 处理筛选条件变化
const handleFilterChange = () => {
  pagination.currentPage = 1
  loadPosts()
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  // 重新加载帖子数据以应用搜索条件
  loadPosts()
}

// 重置筛选
const resetFilters = () => {
  searchQuery.value = ''
  filters.category = ''
  filters.isUrgent = ''
  filters.status = '' // 重置状态筛选
  filters.sortBy = 'createdAt'
  filters.sortOrder = 'desc'
  pagination.currentPage = 1
  loadPosts()
}

// 格式化状态显示
const getStatusText = (status) => {
  const statusMap = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝',
    sold: '已售出'
  }
  return statusMap[status] || status
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 切换紧急状态
const toggleUrgentStatus = async (post) => {
  try {
    // 创建更新数据对象
    const updateData = {
      ...post,
      isUrgent: !post.isUrgent // 切换紧急状态
    }

    // 调用更新接口
    const response = await updatePostService(updateData)
    
    if (response.code === 0) {
      // 更新成功后，更新本地数据
      post.isUrgent = !post.isUrgent
      ElMessage.success('紧急状态更新成功')
    } else {
      ElMessage.error('更新失败: ' + response.msg)
    }
  } catch (error) {
    ElMessage.error('更新失败: ' + error.message)
  }
}

// 查看帖子
const viewPost = async (post) => {
  // 如果帖子的分类ID为4，使用特定接口获取信息并在新窗口中打开WoekDetail页面
  if (post.categoryId === 4) {
    try {
      // 使用getInternshipJobByPostId接口获取实习/兼职信息
      const response = await getInternshipJobByPostId(post.id)
      if (response.code === 0 && response.data) {
        // 在新窗口中打开WoekDetail页面
        // const routeData = router.resolve({ path: `/post/woekdetail/${response.data.id}` })
        // window.open(routeData.href, '_blank')
        router.push({ path: `/admin/posts/woekdetail/${response.data.id}` })
      } else {
        ElMessage.error('获取职位信息失败')
      }
    } catch (error) {
      ElMessage.error('获取职位信息失败: ' + error.message)
    }
  } else {
    // 在新窗口中打开普通帖子详情页面
    // const routeData = router.resolve({ path: `/admin/posts/${post.id}` })
    // window.open(routeData.href, '_blank')
    router.push({ path: `/admin/posts/${post.id}` })
  }
}

// 删除帖子
const deletePost = async (post) => {
  ElMessageBox.confirm(
    `确定要删除帖子 "${post.title}" 吗？此操作不可逆！`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        const response = await deletePostService(post.id)
        if (response.code === 0) {
          ElMessage.success('帖子删除成功')
          loadPosts()
        } else {
          ElMessage.error('删除帖子失败: ' + response.msg)
        }
      } catch (error) {
        ElMessage.error('删除帖子失败: ' + error.message)
      }
    })
    .catch(() => {
      // 用户取消删除
    })
}

// 批量删除帖子
const batchDeletePosts = async () => {
  if (selectedPosts.value.length === 0) {
    ElMessage.warning('请先选择帖子')
    return
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedPosts.value.length} 个帖子吗？此操作不可逆！`,
    '批量删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        // 逐个删除选中的帖子
        let successCount = 0
        for (const postId of selectedPosts.value) {
          try {
            const response = await deletePostService(postId)
            if (response.code === 0) {
              successCount++
            }
          } catch (error) {
            console.error(`删除帖子 ${postId} 失败:`, error)
          }
        }

        ElMessage.success(`成功删除 ${successCount} 个帖子`)
        selectedPosts.value = []
        loadPosts()
      } catch (error) {
        ElMessage.error('批量删除帖子失败: ' + error.message)
      }
    })
    .catch(() => {
      // 用户取消删除
    })
}

// 显示批量修改状态模态框
const showBatchStatusModal = () => {
  if (selectedPosts.value.length === 0) {
    ElMessage.warning('请先选择帖子')
    return
  }
  
  // 显示模态框
  const batchStatusModal = new Modal(document.getElementById('batchStatusModal'))
  batchStatusModal.show()
}

// 批量更新状态
const batchUpdateStatus = async () => {
  if (selectedPosts.value.length === 0) {
    ElMessage.warning('请先选择帖子')
    return
  }

  try {
    // 调用新的批量更新状态接口
    const response = await batchUpdatePostStatusService(selectedPosts.value, batchStatus.newStatus)
    
    if (response.code === 0) {
      // 更新成功后，更新本地数据
      posts.value.forEach(post => {
        if (selectedPosts.value.includes(post.id)) {
          post.status = batchStatus.newStatus
        }
      })
      
      // 关闭模态框
      const batchStatusModalEl = document.getElementById('batchStatusModal')
      const batchStatusModal = Modal.getInstance(batchStatusModalEl) || new Modal(batchStatusModalEl)
      batchStatusModal.hide()
      
      selectedPosts.value = []
      ElMessage.success('帖子状态更新成功')
    } else {
      ElMessage.error('更新失败: ' + response.msg)
    }
  } catch (error) {
    ElMessage.error('批量更新帖子状态失败: ' + error.message)
  }
}

// 批量切换紧急状态
const batchToggleUrgent = async () => {
  if (selectedPosts.value.length === 0) {
    ElMessage.warning('请先选择帖子')
    return
  }

  try {
    // 创建两个数组分别存储需要设为紧急和普通状态的帖子ID
    const postsToUrgent = []
    const postsToNormal = []
    
    // 分别收集需要设为紧急和普通状态的帖子
    posts.value
      .filter(post => selectedPosts.value.includes(post.id))
      .forEach(post => {
        if (post.isUrgent) {
          postsToNormal.push(post.id)
        } else {
          postsToUrgent.push(post.id)
        }
      })
      
    // 批量切换帖子紧急状态
    let successCount = 0
    
    // 批量设为紧急状态
    if (postsToUrgent.length > 0) {
      for (const postId of postsToUrgent) {
        try {
          const post = posts.value.find(p => p.id === postId)
          if (post) {
            const updateData = {
              ...post,
              isUrgent: true
            }
            
            const response = await updatePostService(updateData)
            if (response.code === 0) {
              post.isUrgent = true
              successCount++
            }
          }
        } catch (error) {
          console.error(`更新帖子 ${postId} 紧急状态失败:`, error)
        }
      }
    }
    
    // 批量设为普通状态
    if (postsToNormal.length > 0) {
      for (const postId of postsToNormal) {
        try {
          const post = posts.value.find(p => p.id === postId)
          if (post) {
            const updateData = {
              ...post,
              isUrgent: false
            }
            
            const response = await updatePostService(updateData)
            if (response.code === 0) {
              post.isUrgent = false
              successCount++
            }
          }
        } catch (error) {
          console.error(`更新帖子 ${postId} 紧急状态失败:`, error)
        }
      }
    }
    
    selectedPosts.value = []
    ElMessage.success(`成功切换 ${successCount} 个帖子的紧急状态`)
  } catch (error) {
    ElMessage.error('批量更新帖子紧急状态失败: ' + error.message)
  }
}

// 生命周期
onMounted(() => {
  loadPosts()
  loadCategories()
})
</script>

<style scoped>
.page-title {
  color: #2c3e50;
  font-weight: 600;
}

.stat-card {
  border: none;
  border-radius: 12px;
  transition: transform 0.2s;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-icon {
  font-size: 2.5rem;
  opacity: 0.8;
}

.table th {
  border-top: none;
  font-weight: 600;
  color: #6c757d;
  font-size: 0.875rem;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.table-hover>tbody>tr:hover>td {
  background-color: #e3f2fd !important;
}

.table>tbody>tr {
  transition: background-color 0.2s ease;
}

.status-badge {
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.75rem;
  font-weight: 600;
  display: inline-block;
}

.status-pending {
  background-color: #f8f9fa;
  color: #6c757d;
  border: 1px solid #6c757d;
}

.status-approved {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.status-rejected {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.status-sold {
  background-color: #d1ecf1;
  color: #0c5460;
  border: 1px solid #bee5eb;
}

.form-check-input-lg {
  width: 1.5em;
  height: 1.5em;
  margin-top: 0;
  border: 2px solid #0d6efd;
  transition: all 0.2s ease;
}

.form-check-input-lg:checked {
  border: 3px solid #0d6efd;
  background-color: #0d6efd;
}

.form-check {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 0;
}

.form-check-label {
  cursor: pointer;
  user-select: none;
}

.batch-actions {
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  border-top: 3px solid #0d6efd !important;
  animation: slideInUp 0.3s ease-out;
}

@keyframes slideInUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

/* 批量修改状态模态框样式 */
.modal-content {
  border-radius: 12px;
  overflow: hidden;
}

.modal-header {
  border-bottom: none;
  padding: 1.5rem;
}

.modal-body {
  padding: 1.5rem;
}

.modal-footer {
  border-top: none;
  padding: 1.5rem;
}

.form-select-lg {
  padding: 0.75rem 1rem;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  transition: all 0.2s ease;
}

.form-select-lg:focus {
  border-color: #86b7fe;
  box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
}

.form-label {
  margin-bottom: 0.5rem;
  font-weight: 500;
}

.form-text {
  font-size: 0.875rem;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .table-responsive {
    font-size: 0.875rem;
  }

  .btn-group-sm>.btn {
    padding: 0.25rem 0.5rem;
  }

  .stat-card .card-title {
    font-size: 1.25rem;
  }
  
  .modal-dialog {
    margin: 1rem;
  }
}
</style>
